<?php
class User_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
		$this->load->database();
	}
	
	/**
	 * 新建一个用户
	 * @param $name
	 * @param $email_add
	 * @param $password
	 * @return 用户id
	 */
	public function add_user($name,$email_add,$password){
		$date_now = date('Y-m-d');
		
		$data = array(
				'uname' => $name,
				'email' => $email_add,
				'password' => $password,
				'registerdate' => $date_now
		);
		
		$this->db->insert('user', $data);
		return $this->db->insert_id();
	}
	
	
	public function get_user($id = 0) {
		
		$this->db->where('uid',$id);
		$this->db->select('uid,uname,email,registerdate');
		$query = $this->db->get('user');
		
		if ($query->num_rows() > 0) {
			return (array)$query->row();
		}else {
			return null;
		}
	}
	
	/**
	 * 通过邮箱与密码验证用户
	 * @param $email
	 * @param $password
	 * @return boolean
	 */
	public function validate_user($email,$password) {
		$this->db->select('uid');
		$this->db->where('email',$email);
		$this->db->where('password',$password);
		$query = $this->db->get('user');
		return $query->num_rows() > 0;
	}
	
	/**
	 * 返回制定email对应的用户id
	 * @param $email
	 * @return 用户id,当用户不存在返回空值
	 */
	public function get_id_by_email($email){
		return $this->get_id_where('email',$email);
	}
	
	/**
	 * 返回制定用户名对应的用户id
	 * @param $name
	 * @return 用户id,当用户不存在返回空值
	 */
	
	public function get_id_by_name($name){
		return $this->get_id_where('uname',$name);
	}
	
	/**
	 * 查询符合指定条件的用户id
	 * @param $field 用来查询的字段
	 * @param $value 字段的值
	 * @return 用户id,当用户不存在返回空值
	 */
	private function get_id_where($field,$value){
		$this->db->select('uid');
		$this->db->where($field,$value);
		$query = $this->db->get('user');
		if($query->row())
			return $query->row()->uid;
		else
			return null;
	}
}

?>